import React, { useState, useEffect, useRef } from "react";
import { Form, Button, Input, Affix, Select, message, Space, Switch, Drawer, Row, Col } from "antd";
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { useModelAssociateMapping, useModelAssociateType} from "@/components";
import cmdbres from "@/data/cmdbres";
import hcpiam from "@/data/hcpiam";
import request, {requestIAM} from '@/utils/request';
import regexpUtil from "@/utils/regexpUtil";
import hcpUtils from "@/utils/hcpUtils";

const { uniqueIdentificationRegexp } = regexpUtil;
const user = hcpUtils.getUser();
const CreateRelation = ({ history, visible, setVisible, onCreateFinish, info, targetData }) => {
    const [loading, setLoading] = useState(false);
    const [mapping] = useModelAssociateMapping();
    const [{associateTypeData}] = useModelAssociateType();
    const [sourceModelData, setSourceModelData] = useState([]);
    const [targetModelData, setTargetModelData ] = useState([]);
    const [selectTypeValues, setSelectTypeValues] = useState({});
    const [destModuleId, setDestModuleId] = useState({'destModuleId':undefined});
	const [form] = Form.useForm();

    // const queryKindModule = async () => {
    //     try {
    //         let res = await request({
    //             ...cmdbres.queryKindModule,
    //         });
    //         if (res && res.code == 200) {

    //             form.setFieldsValue({
    //                 sourceModel: info.moduleCode
    //             })
    //             changeType('srcModuleId', info.moduleCode, {
    //                 srcModuleId: info.moduleId,
    //                 srcModuleCode: info.moduleCode,
    //                 srcModuleName: info.moduleName
    //             });

    //             let data = res.data?.filter(item => item.cmModuleId !== info.moduleId);
    //             setSourceModelData(res.data);
    //             setTargetModelData(data);
    //         }
    //     } catch (error) {
    //         console.log(error);
    //     }
    // }

    useEffect(() => {
        if(visible) {
            // queryKindModule();
            let typeValues = {};
            if(info) {
                form.setFieldsValue({
                    sourceModel: info.moduleCode
                })
                setSourceModelData([{
                    ...info,
                    cmModuleId: info.moduleId,
                }]);
                Object.assign(typeValues, {
                    srcModuleId: info.moduleId,
                    srcModuleCode: info.moduleCode,
                    srcModuleName: info.moduleName
                })
            }
            if(targetData && targetData.length) {
                setTargetModelData(targetData);
                const f = targetData[0];
                form.setFieldsValue({
                    targetModel: f.moduleCode
                })
                Object.assign(typeValues, {
                    destModuleId: f.moduleId || f.cmModuleId,
                    destModuleCode: f.moduleCode,
                    destModuleName: f.moduleName
                })
            }
            setSelectTypeValues(typeValues);
        }
    }, [visible, info, targetData]);

	const onFinish = async (fieldsValue) => {
        setLoading(true);
        let param = {
            moduleAssociateCode: fieldsValue.moduleAssociateCode,
            moduleAssociateName: fieldsValue.moduleAssociateName,
            description: fieldsValue.description,
            namespace: 'default',
            author: user.staffName,
            srcModuleId: '',
            srcModuleCode: '',
            srcId: '',
            ...selectTypeValues
        }
        if(!param?.destModuleId){
            param.destModuleId =   destModuleId;
        }
		let res = await request({
			...cmdbres.createModelAssociate,
			data: param
		});
		setLoading(false);
		if (res && res.code == 200) {
			setVisible(false);
			message.success("新建关联成功！");
			if (typeof onCreateFinish == "function") onCreateFinish(res);
		}
	};

	const changeType = (type, value, option) => {
        let selectType = {...selectTypeValues};
        if(option) {
            Object.assign(selectType, option);
        } else {
            selectType[type] = value;
        }
        setSelectTypeValues(selectType);

        if(type == 'destModuleId'){
            setDestModuleId({ 'destModuleId': option.destModuleId})
        }

        if(selectType.destModuleCode && selectType.associateType) {
            form.setFieldsValue({
                moduleAssociateCode: `${selectType.srcModuleCode}_${selectType.associateType}_${selectType.destModuleCode}`
            })
        }
    }

    const handleClose = () => {
        setVisible(false);
        if (typeof onCreateFinish == "function") onCreateFinish(false);
    }

    return (
        <Drawer 
            className="drawer-table-columns create-field"
            title={'添加关联'}
            placement={'right'}
            width={600}
            onClose={handleClose}
            visible={visible}
            footer={null}
        >
            <Form
                className="hcp-drawer-form"
                form={form}
                labelCol={{ span: 5}}
                wrapperCol={{ span: 17 }}
                name="basic"
                onFinish={onFinish}
            >

                <Form.Item
                    label="目标模型"
                    name="targetModel"
                    key="targetModel"
                    rules={[{required: true,message: '请选择目标模型'}]}
                >
                    <Select
                        placeholder="请选择"
                        style={{ width: "100%", marginRight: 10 }}
                        onChange={(value, option) => {
                            changeType('destModuleId', value, {
                                destModuleId: option.key,
                                destModuleCode: option.value,
                                destModuleName: option.name
                            });
                        }}
                        showSearch
                    >
                        {
                            targetModelData?.map((item, index) => (
                                <Select.Option
                                    key={item.cmModuleId}
                                    value={item.moduleCode}
                                    name={item.moduleName}
                                >
                                    {item.moduleName}
                                </Select.Option>
                            ))
                        }
                    </Select>
                </Form.Item>
                <Form.Item
                    label="关联类型"
                    name="associateType"
                    key="associateType"
                    rules={[{required: true,message: '请选择关系类型'}]}
                >
                    <Select
                        placeholder="请选择"
                        style={{ width: "100%", marginRight: 10 }}
                        onChange={(value) => changeType('associateType', value)}
                    >
                        {
                            associateTypeData?.map((item, index) => (
                                <Select.Option
                                    key={item.associateTypeCode}
                                    value={item.associateTypeCode}
                                    disabled={item.associateTypeCode == "cm_mainline"}
                                >
                                    {item.name}
                                </Select.Option>
                            ))
                        }
                    </Select>
                </Form.Item>


                 <Form.Item 
                    label="模型关联ID"
                    name="moduleAssociateCode"
                    rules={[
                           {
                            required: true,
                            message: '唯一标识不能为空',
                        },
                        uniqueIdentificationRegexp(256),
                    ]}
                    // extra={
                    //     <p style={{ color: "#999999" }}>
                    //         请填写以字母开头，数字、字母、下划线，横线的组合
                    //     </p>
                    // }
                    // style={{ marginBottom: 5 }}
                    >
                    <Input placeholder="请输入模型关联ID" maxLength={256} readOnly />
                </Form.Item>
                <Form.Item 
                    label="模型关联名称"
                    name="moduleAssociateName" 
                    rules={[{required: true,message: '请输入字段名称'}]}
                >
                    <Input placeholder="请输入字段名称" maxLength={64} />
                </Form.Item>
                <Form.Item
                    label="源模型"
                    name="sourceModel"
                    key="sourceModel"
                    rules={[{required: true,message: '请选择源模型'}]}
                    style={
                        { display:'none'}
                    }

                >
                    <Select
                        placeholder="请选择"
                        style={{ width: "100%", marginRight: 10 }}
                        disabled
                    >
                        {
                            sourceModelData?.map((item, index) => (
                                <Select.Option
                                    key={item.cmModuleId}
                                    value={item.moduleCode}
                                    name={item.moduleName}
                                >
                                    {item.moduleName}
                                </Select.Option>
                            ))
                        }
                    </Select>
                </Form.Item>
                {/*<Form.Item*/}
                {/*    label="目标模型"*/}
                {/*    name="targetModel"*/}
                {/*    key="targetModel"*/}
                {/*    rules={[{required: true,message: '请选择目标模型'}]}*/}
                {/*>*/}
                {/*    <Select*/}
                {/*        placeholder="请选择"*/}
                {/*        style={{ width: "100%", marginRight: 10 }}*/}
                {/*        onChange={(value, option) => {*/}
                {/*            changeType('destModuleId', value, {*/}
                {/*                destModuleId: option.key,*/}
                {/*                destModuleCode: option.value,*/}
                {/*                destModuleName: option.name*/}
                {/*            });*/}
                {/*        }}*/}
                {/*        showSearch*/}
                {/*    >*/}
                {/*        {*/}
                {/*            targetModelData?.map((item, index) => (*/}
                {/*                <Select.Option*/}
                {/*                    key={item.cmModuleId}*/}
                {/*                    value={item.moduleCode}*/}
                {/*                    name={item.moduleName}*/}
                {/*                >*/}
                {/*                    {item.moduleName}*/}
                {/*                </Select.Option>*/}
                {/*            ))*/}
                {/*        }*/}
                {/*    </Select>*/}
                {/*</Form.Item>*/}
                {/*<Form.Item*/}
                {/*    label="关联类型"*/}
                {/*    name="associateType"*/}
                {/*    key="associateType"*/}
                {/*    rules={[{required: true,message: '请选择关系类型'}]}*/}
                {/*>*/}
                {/*     <Select*/}
                {/*        placeholder="请选择"*/}
                {/*        style={{ width: "100%", marginRight: 10 }}*/}
                {/*        onChange={(value) => changeType('associateType', value)}*/}
                {/*    >*/}
                {/*        {*/}
                {/*             associateTypeData?.map((item, index) => (*/}
                {/*                <Select.Option*/}
                {/*                    key={item.associateTypeCode}*/}
                {/*                    value={item.associateTypeCode}*/}
                {/*                    disabled={item.associateTypeCode == "cm_mainline"}*/}
                {/*                >*/}
                {/*                    {item.name}*/}
                {/*                </Select.Option>*/}
                {/*            ))*/}
                {/*        }*/}
                {/*    </Select>*/}
                {/*</Form.Item>*/}
                <Form.Item
                    label="源-目标约束"
                    name="modelMapping"
                    key="modelMapping"
                    rules={[{required: true,message: '请选择源-目标约束'}]}
                >
                    <Select
                        placeholder="请选择"
                        style={{ width: "100%", marginRight: 10 }}
                        onChange={(value) => {
                            changeType('mapping', value);
                        }}
                    >
                        {
                            mapping?.map((item, index) => (
                                <Select.Option
                                    key={index}
                                    value={item}
                                >
                                    {item}
                                </Select.Option>
                            ))
                        }
                    </Select>
                </Form.Item>
                <Form.Item
                    label="关联描述"
                    name="description"
                    key="description"
                >
                    <Input.TextArea />
                </Form.Item>
                <div className="modal-body-footer">
                    <Space>
                        <Button type="primary" htmlType="submit" loading={loading}>提交</Button>
                        <Button onClick={handleClose}>取消</Button>
                    </Space>
                </div>
            </Form>
        </Drawer>
    );
};

export default CreateRelation;